using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Web.WebView2.Core;

namespace WebBrowserApp
{
    public class PageInfoCaptureService
    {
        public async Task<PageInfo> CapturePageInfoAsync(CoreWebView2 webView)
        {
            var pageInfo = new PageInfo
            {
                Url = webView.Source,
                LoadTime = DateTime.Now
            };

            try
            {
                // 获取页面标题
                pageInfo.Title = await ExecuteScriptAsync(webView, "document.title");

                // 获取完整HTML
                pageInfo.HtmlContent = await ExecuteScriptAsync(webView, 
                    "document.documentElement.outerHTML");

                // 获取文本内容
                pageInfo.TextContent = await ExecuteScriptAsync(webView, 
                    "document.body.innerText || document.body.textContent || ''");

                // 获取所有链接
                var linksJson = await ExecuteScriptAsync(webView, @"
                    (function() {
                        var links = Array.from(document.querySelectorAll('a[href]'));
                        return JSON.stringify(links.map(a => a.href));
                    })()
                ");
                pageInfo.Links = ParseJsonArray(linksJson);
                pageInfo.LinkCount = pageInfo.Links.Count;

                // 获取所有图片
                var imagesJson = await ExecuteScriptAsync(webView, @"
                    (function() {
                        var images = Array.from(document.querySelectorAll('img'));
                        return JSON.stringify(images.map(img => img.src || img.getAttribute('data-src') || ''));
                    })()
                ");
                pageInfo.Images = ParseJsonArray(imagesJson).Where(img => !string.IsNullOrEmpty(img)).ToList();
                pageInfo.ImageCount = pageInfo.Images.Count;

                // 获取表单数量
                var formCountJson = await ExecuteScriptAsync(webView, 
                    "document.querySelectorAll('form').length.toString()");
                if (int.TryParse(formCountJson?.Trim('"'), out int formCount))
                {
                    pageInfo.FormCount = formCount;
                }

                // 获取Meta标签
                var metaJson = await ExecuteScriptAsync(webView, @"
                    (function() {
                        var metas = document.querySelectorAll('meta');
                        var result = {};
                        metas.forEach(meta => {
                            var name = meta.getAttribute('name') || meta.getAttribute('property') || meta.getAttribute('http-equiv');
                            var content = meta.getAttribute('content');
                            if (name && content) {
                                result[name] = content;
                            }
                        });
                        return JSON.stringify(result);
                    })()
                ");
                pageInfo.MetaTags = ParseJsonObject(metaJson);

                // 获取脚本数量
                var scriptCountJson = await ExecuteScriptAsync(webView, 
                    "document.querySelectorAll('script').length.toString()");
                if (int.TryParse(scriptCountJson?.Trim('"'), out int scriptCount))
                {
                    pageInfo.ScriptCount = scriptCount;
                }

                // 获取样式表数量
                var styleCountJson = await ExecuteScriptAsync(webView, 
                    "document.querySelectorAll('link[rel=\"stylesheet\"], style').length.toString()");
                if (int.TryParse(styleCountJson?.Trim('"'), out int styleCount))
                {
                    pageInfo.StyleSheetCount = styleCount;
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"抓取页面信息时出错: {ex.Message}", ex);
            }

            return pageInfo;
        }

        private async Task<string> ExecuteScriptAsync(CoreWebView2 webView, string script)
        {
            try
            {
                var result = await webView.ExecuteScriptAsync(script);
                // 移除JSON字符串的引号
                if (result != null && result.StartsWith("\"") && result.EndsWith("\""))
                {
                    result = result.Substring(1, result.Length - 2);
                    // 处理转义字符
                    result = result.Replace("\\\"", "\"").Replace("\\n", "\n").Replace("\\r", "\r").Replace("\\\\", "\\");
                }
                return result ?? string.Empty;
            }
            catch (Exception ex)
            {
                throw new Exception($"执行脚本失败: {ex.Message}", ex);
            }
        }

        private List<string> ParseJsonArray(string json)
        {
            if (string.IsNullOrEmpty(json) || json == "null")
                return new List<string>();

            try
            {
                // 移除可能的引号包装
                json = json.Trim('"');
                // 处理转义
                json = System.Text.RegularExpressions.Regex.Unescape(json);
                
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };
                return JsonSerializer.Deserialize<List<string>>(json, options) ?? new List<string>();
            }
            catch
            {
                // 如果JSON解析失败，尝试手动解析
                try
                {
                    json = json.Trim('[', ']');
                    var items = json.Split(',')
                        .Select(s => s.Trim().Trim('"'))
                        .Where(s => !string.IsNullOrEmpty(s))
                        .ToList();
                    return items;
                }
                catch
                {
                    return new List<string>();
                }
            }
        }

        private Dictionary<string, string> ParseJsonObject(string json)
        {
            if (string.IsNullOrEmpty(json) || json == "null")
                return new Dictionary<string, string>();

            try
            {
                // 移除可能的引号包装
                json = json.Trim('"');
                // 处理转义
                json = System.Text.RegularExpressions.Regex.Unescape(json);
                
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };
                return JsonSerializer.Deserialize<Dictionary<string, string>>(json, options) 
                    ?? new Dictionary<string, string>();
            }
            catch
            {
                return new Dictionary<string, string>();
            }
        }
    }
}

